package com.javasm.commons.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisConfig {

  private Logger log = LoggerFactory.getLogger(RedisConfig.class);

    @Value("${spring.redis.host}")
	private String ipHost;
	@Value("${spring.redis.port}")
	private int port;

	@Value("${spring.redis.password}")
	private String password;

	@Value("${spring.redis.timeout}")
	private int timeout;

    @Bean("redisTemplate")  // 通过@bean注解定义RedisTemplate对象  自定义指定redis序列化方式  （默认jdk序列化，可读性差）
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置键的序列化方式为String
        template.setKeySerializer(RedisSerializer.string());
        // 设置值的序列化方式为JdkSerializationRedisSerializer（或其他合适的序列化方式）
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());

        template.afterPropertiesSet();
        return template;
    }

//    //设置redis失效时间
//    @Resource    //注入封装缓存RedisTemplate对象，设置缓存失效时间
//    private RedisTemplate<String, Object> redisTemplate;
//
//    public void setExpire(String key,String value, long expire, TimeUnit timeUnit) {
//        redisTemplate.opsForValue().set(key, value,expire, TimeUnit.SECONDS);
//    }
//
//    public void set(String key, Object value) {//注入封装缓存RedisTemplate对象，获取缓存对象
//        redisTemplate.opsForValue().set(key, value);
//    }
//
//    public Object get(String key) { //注入封装缓存RedisTemplate对象，获取缓存对象
//        return redisTemplate.opsForValue().get(key);
//    }

}
